package com.ext.aic.components;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

public class StaggeredGridSpacingItemDecoration extends RecyclerView.ItemDecoration {
    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public StaggeredGridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // 获取当前项的位置
        if (position >= 0) {
            int spanIndex = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
            // 左右间距处理
            if (includeEdge) {
                // 左边距：第一列左边缘有间距，否则间距在中间
                if (spanIndex == 0) {
                    outRect.left = spacing;
                    outRect.right = spacing / 2;
                } else {
                    outRect.left = spacing / 2;
                    outRect.right = spacing;
                }
            } else {
                outRect.left = (spanIndex == 0) ? 0 : spacing / 2;
                outRect.right = (spanIndex == spanCount - 1) ? 0 : spacing / 2;
            }
            // 上下间距处理（所有项底部添加间距，顶部由上方项的底部间距覆盖）
            if (position >= spanCount) {
                outRect.top = spacing;
            }
        }
    }
}
